package top.ucat.x.service.uaa.server.service;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.RegistryConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import top.ucat.box.cloud.common.exception.BaseException;
import top.ucat.box.cloud.dubbo.common.util.DubboUtil;
import top.ucat.box.starter.oauth.common.bean.entity.OauthUserCredentials;
import top.ucat.box.starter.oauth.common.bean.oauth.UserCredentialBo;
import top.ucat.box.starter.oauth.common.pojo.User;
import top.ucat.box.starter.oauth.common.service.UcatUserDetailsService;
import top.ucat.x.service.uaa.server.property.DynamicSystemLoginProperties;
import top.ucat.x.system.entity.SysUser;
import top.ucat.x.uaa.service.bean.SystemUser;
import top.ucat.x.uaa.service.provider.UserAuthenticationService;

import java.util.ArrayList;

/**
 * @Auther: Jun
 * @Date: 2020/3/25 16:26
 * @Description:
 */
@Service
public class UcatUserDetailsServiceImpl implements UcatUserDetailsService {

    @Autowired
    private RegistryConfig registryConfig;

    @Autowired
    private DynamicSystemLoginProperties dynamicSystemLoginProperties;

    @Override
    public UserDetails loadUser(UserCredentialBo credentialBo) throws UsernameNotFoundException {
        Class serviceClass = null;
        try {
            String systemLoginCLassPath = dynamicSystemLoginProperties.getSystemLoginCLassPath(credentialBo.getSystemType());
            if (StringUtils.isBlank(systemLoginCLassPath)) {
                throw new ClassNotFoundException();
            }
            serviceClass = Class.forName(systemLoginCLassPath);
            UserAuthenticationService userAuthenticationService = (UserAuthenticationService) DubboUtil.getDubboBean(serviceClass, this.registryConfig);
            SystemUser user = userAuthenticationService.getUser(credentialBo);
            SysUser sysUser = (SysUser) user.getUser();

            User oauthUser = new User();
            oauthUser.setUsername(user.getUsername());
            oauthUser.setPassword(user.getPassword());
            oauthUser.setId(sysUser.getId());
            oauthUser.setUser(sysUser);
            return oauthUser;
        } catch (ClassNotFoundException e) {
            throw new BaseException("没有配置");
        }
    }

}
